from model.article import Article
from base.database import Mysql


class Db(Mysql):
    def __init__(self, debug=False):
        super().__init__(database="voice", debug=debug)
        self.article_table = "article"

    def save_article(self, article):
        article.set("content", None)
        return self.insert(self.article_table, article, ignore=True)

    def list_uncrawled_article(self):
        return self.list_model(self.article_table, Article, "content is null")

    def list_uncrawled_url(self, source, category, date_limit=None):
        clause = "content is null"
        if source.strip() != "":
            clause += " and source='" + source + "'"
        if category.strip() != "":
            clause += " and category='" + category + "'"
        if date_limit is not None:
            clause += " and (createdate is null or createdate>'" + date_limit + "')"
        else:
            clause += " and createdate is null"
        return self.list(self.article_table, "id, url", clause)

    def replace_article(self, article):
        return self.replace_into(self.article_table, article)

    def update_field_by_url(self, field, value, url):
        return self.update(self.article_table, field, value, "url=" + self.get_value(url))

    def del_by_url(self, url):
        return self.delete(self.article_table, "url=" + self.get_value(url))


if __name__ == '__main__':
    import time

    today = time.strftime("%Y-%d-%m")
    yesterday = time.strftime("%Y-%d-%m", time.localtime(time.time() - 3600 * 24))
    print(today)
    print(yesterday)
    db = Db(debug=True)
    for url in db.list_uncrawled_url("博讯网", "china", yesterday):
        print(url)
